package com.tbl.modules.wms2.controller.insidewarehouse;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.wms.dao.baseinfo.FactoryAreaDAO;
import com.tbl.modules.wms.dao.baseinfo.WarehouseDAO;
import com.tbl.modules.wms.dao.interfacelog.InterfaceLogDAO;
import com.tbl.modules.wms.entity.baseinfo.Warehouse;
import com.tbl.modules.wms2.common.RuleCode;
import com.tbl.modules.wms2.constant.Constant;
import com.tbl.modules.wms2.dao.baseinfo.BaseDataDao;
import com.tbl.modules.wms2.dao.insidewarehouse.transferorder.TransferOrderDAO;
import com.tbl.modules.wms2.dao.insidewarehouse.transferorder.TransferOrderLineDAO;
import com.tbl.modules.wms2.entity.insidewarehouse.transferorder.TransferOrderEntity;
import com.tbl.modules.wms2.entity.insidewarehouse.transferorder.TransferOrderLineEntity;
import com.tbl.modules.wms2.entity.operation.*;
import com.tbl.modules.wms2.entity.ordermanage.asn.AsnLineEntity;
import com.tbl.modules.wms2.entity.purchasein.PurchaseOrderSaveEntity;
import com.tbl.modules.wms2.entity.report.YclInventoryEntity;
import com.tbl.modules.wms2.service.baseinfo.OrganizeService;
import com.tbl.modules.wms2.service.common.CountService;
import com.tbl.modules.wms2.service.insidewarehouse.transferorder.TransferOrderLineService;
import com.tbl.modules.wms2.service.insidewarehouse.transferorder.TransferOrderService;
import com.tbl.modules.wms2.service.operation.OperationOtherService;
import com.tbl.modules.wms2.service.operation.YclInOutFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 移位移库单
 */
@Controller()
@RequestMapping("/ycl/insidewarehouse/transferOrder")
public class TransferOrderController extends AbstractController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private TransferOrderService transferOrderService;
    @Resource
    private TransferOrderDAO transferOrderDAO;
    @Resource
    private TransferOrderLineDAO transferOrderLineDAO;
    @Autowired
    private TransferOrderLineService transferOrderLineService;
    @Resource
    private FactoryAreaDAO factoryAreaDAO;
    @Resource
    private WarehouseDAO warehouseDAO;
    @Resource
    private BaseDataDao baseDataDao;
    @Autowired
    private OperationOtherService otherService;
    /**
     * 接口日志
     */
    @Autowired
    private InterfaceLogDAO interfaceLogDAO;

    @Resource
    YclInOutFlowService yclInOutFlowService;
    @Resource
    private CountService countService;
    @Resource
    private OrganizeService organizeService;
    /**
     * 保存移库调拨单
     *
     * @param
     * @return Map<String, Object>
     */
    @PostMapping(value = "/save")
    @ResponseBody
    @Transactional
    public Map<String, Object> save(@RequestBody TransferOrderEntity transferEntity) {
        if(transferEntity==null || transferEntity.getTranType()==null || transferEntity.getLine()==null || transferEntity.getLine().isEmpty()){
            return null;
        }
        List<TransferOrderLineEntity> lines = transferEntity.getLine();
        String tranType = String.valueOf(transferEntity.getTranType());
        Integer fromEntityId = Integer.parseInt(transferEntity.getFromAreaCode());
        String toEntityId = null;

        if (tranType.equals("3"))//调拨
        {
            String tranCode = countService.getNextCount("DBDH");
            transferEntity.setTranCode(tranCode);
            toEntityId = transferEntity.getToAreaCode();
        }else{
            String tranCode = countService.getNextCount("YWDH");
            transferEntity.setTranCode(tranCode);
            toEntityId = String.valueOf(fromEntityId);
        }
        transferEntity.setToAreaCode(toEntityId);
        //获取头表主键ID
        String id = new String();
        if(StringUtils.isEmpty(transferEntity.getId())){
            id = String.valueOf(transferOrderDAO.getSequence());
            transferEntity.setId(id);
        }else{
            id = transferEntity.getId();
        }
        transferEntity.setCreateTime(DateUtil.date().toString());
        transferEntity.setStatus("0");

        //获取来源厂区名称
        List<Map<String,Object>> fromList = baseDataDao.getAreaList(fromEntityId);
        String fromArea = String.valueOf(fromList.get(0).get("text"));
        transferEntity.setFromArea(fromArea);

        //获取目标厂区名称
        List<Map<String,Object>> toList = baseDataDao.getAreaList(Integer.valueOf(toEntityId));
        String toArea = String.valueOf(toList.get(0).get("text"));
        transferEntity.setToArea(toArea);

        //获取来源仓库名
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("entityId",fromEntityId);
        paramMap.put("storeCode",String.valueOf(transferEntity.getFromStoreCode()));
        List<Map<String,Object>> fromStoreList = baseDataDao.getStores(paramMap);
        String fromStore = String.valueOf(fromStoreList.get(0).get("text"));
        transferEntity.setFromStore(fromStore);

        //获取目的仓库名
        paramMap.clear();
        paramMap.put("entityId",Integer.valueOf(toEntityId));
        paramMap.put("storeCode",String.valueOf(transferEntity.getToStoreCode()));
        List<Map<String,Object>> toStoreList = baseDataDao.getStores(paramMap);
        String toStore = String.valueOf(toStoreList.get(0).get("text"));
        transferEntity.setToStore(toStore);

        //保存头表信息

        int iHead = transferOrderDAO.insert(transferEntity);

        //保存子表信息
        List<TransferOrderLineEntity> transferOrderLineEntityList = new ArrayList<>(lines.size());
        for(int i=0;i<lines.size();i++){
            TransferOrderLineEntity line = lines.get(i);
            line.setTranId(id);
            line.setUpdateTime(DateUtil.parseDateTime(DateUtil.now()));
            line.setLineState("0");
            transferOrderLineEntityList.add(line);
        }
        boolean result = (iHead==1 && transferOrderLineService.saveBatch(transferOrderLineEntityList));

        Map resultMap = new HashMap(2);
        resultMap.put("result", result);
        resultMap.put("msg", result ? "操作成功！" : "操作失败！");
        return resultMap;
    }

    /**
     * 更改订单行状态（0:待处理，1:已上架）
     * @param lineId
     * @param lineState
     * @return
     */
    @RequestMapping(value = "/updateLineState", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> updateLineState(@RequestParam("lineId") String lineId,@RequestParam("lineState") String lineState){
        Map<String, Object> map = new HashMap<>(4);
        TransferOrderLineEntity transferOrderLineEntity = transferOrderLineService.findById(lineId);
        transferOrderLineEntity.setLineState(lineState);
        int result = transferOrderLineDAO.updateById(transferOrderLineEntity);
        if(result==1){
            map.put("code", 0);
            map.put("msg", "success");
        }else{
            map.put("code", 1);
            map.put("msg", "not found lineId");
        }
        return map;
    }

    /**
     * 更改订单行状态（0:待处理，1:已上架）
     * @param id
     * @param state
     * @return
     */
    @RequestMapping(value = "/updateHeadState", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> updateHeadState(@RequestParam("id") String id,@RequestParam("state") String state){
        Map<String, Object> map = new HashMap<>(4);
        TransferOrderEntity transferOrderEntity = transferOrderService.findById(id);
        transferOrderEntity.setStatus(state);
        int result = transferOrderDAO.updateById(transferOrderEntity);
        if(result==1){
            map.put("code", 0);
            map.put("msg", "success");
        }else{
            map.put("code", 1);
            map.put("msg", "not found lineId");
        }
        return map;
    }

    @PostMapping(value = "/edit")
    @ResponseBody
    @Transactional
    public Map<String, Object> edit(@RequestBody TransferOrderEntity transferEntity) {
        if(transferEntity==null || StringUtils.isEmpty(transferEntity.getLineId())){
            return null;
        }
        Map resultMap = new HashMap();
        //删除行表数据
        String lineId = transferEntity.getLineId();
        Map<String,Object> map = new HashMap<>();
        map.put("LINE_ID",lineId);
        List<TransferOrderLineEntity> list = transferOrderLineService.getTransferOrderLines(map);

        for(int i=0;i<list.size();i++){
            transferOrderService.delete(list.get(i).getLineId());
        }

        resultMap = this.save(transferEntity);

        return resultMap;

    }

    /**
     * 删除
     *
     * @param
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/deleteByLineIds")
    @ResponseBody
    @Transactional
    public Map<String, Object> delete(String lineIds) {
        Map<String, Object> map = new HashMap<>(2);
        String[] aLineIds = lineIds.split(",");
        boolean bh = true;
        //根据行lineId获取tranId,并通过tranId查询满足条件的行表list,如果list大小为1，说明同时要删除头表信息
        for(int i=0;i<aLineIds.length;i++){
            TransferOrderLineEntity lineEntity = transferOrderLineService.findById(aLineIds[i]);
            String tranId = lineEntity.getTranId();
            Map<String,Object> findMap = new HashMap<>();
            findMap.put("TRAN_ID",tranId);
            List<TransferOrderLineEntity> lineList = transferOrderLineService.getTransferOrderLines(findMap);
            int bLine = 0;
            if(lineList.size()==1){
                bLine = transferOrderLineDAO.deleteById(aLineIds[i]);
                bh = transferOrderService.delete(tranId);
            }else{
                bLine = transferOrderLineDAO.deleteById(aLineIds[i]);
            }

            if(bLine<1 && bh){
                map.put("result", false);
                map.put("msg", "操作失败！");
                return map;
            }
        }
        map.put("result", true);
        map.put("msg", "操作成功！");
        return map;
    }

    /**
     * 删除
     *
     * @param
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/deleteByHeadId")
    @ResponseBody
    @Transactional
    public Map<String, Object> deleteHead(String id) {
        Map<String, Object> map = new HashMap<>(2);
        boolean bh = transferOrderService.delete(id);
        if(!bh){
            map.put("result", false);
            map.put("msg", "操作失败！");
            return map;
        }
        map.put("result", true);
        map.put("msg", "操作成功！");
        return map;
    }

    /**
     * 跳转Grid列表页
     *
     * @return
     */
    @RequestMapping(value = "/toMove")
    public ModelAndView toRewindList() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/insidewarehouse/transferorder/move");
        return mv;
    }


    /**
     * 跳转Grid列表页
     *
     * @return
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toRewindListUp() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/insidewarehouse/transferorder/list");
        return mv;
    }

    /**
     * 获取Grid列表数据
     *
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list(TransferOrderEntity transferOrderEntity) {
        Map<String, Object> paramsMap = getAllParameter();
        return transferOrderService.getPageList(paramsMap);
    }


    @RequestMapping(value = "/headList")
    @ResponseBody
    public Map<String,Object> headList(TransferOrderEntity transferOrderEntity){
        Map<String, Object> paramsMap = getAllParameter();
        return transferOrderService.getHeadPageList(paramsMap);
    }

    /**
     * 弹出到明细页面
     *
     * @param tranId 主表主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/toDetailList")
    @ResponseBody
    public ModelAndView toDetailList(Long tranId) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/operation/transfer/tran_store_detail");
        mv.addObject("tranId", tranId);
        return mv;
    }

    /**
     * 弹出到新增/编辑页面
     * @return
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public ModelAndView toAdd() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/insidewarehouse/transferorder/edit");

        return mv;
    }

    /**
     * 打印页面
     * @return
     */
    @RequestMapping("/toPrint")
    @ResponseBody
    public ModelAndView toPrint() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/insidewarehouse/transferorder/print");

        return mv;
    }

    @RequestMapping("/toPrintIn")
    @ResponseBody
    public ModelAndView toPrintIn() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/insidewarehouse/transferorder/printIn");

        return mv;
    }
    /**
     * 弹出到新增/编辑页面
     * @return
     */
    @RequestMapping("/moveEdit")
    @ResponseBody
    public ModelAndView toMove() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/insidewarehouse/transferorder/moveEdit");

        return mv;
    }

    @RequestMapping(value = "/getTransferOrderById")
    @ResponseBody
    public Map<String,Object> getTransferOrderById(String tranId) {
        TransferOrderEntity transferOrderEntity = transferOrderService.findById(tranId);
        Map<String, Object> map = new HashMap<>(3);
        map.put("msg", "success");
        map.put("result", true);
        map.put("data", transferOrderEntity);
        return map;
    }

    /**
     * 跳转到移库调拨上架页面
     * @return
     */
    @RequestMapping(value = "/toListUp")
    public ModelAndView toListUp() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/insidewarehouse/transferorder/list_up");
        return mv;
    }

    /**
     * 获取移库时待入库数据
     * @param transferOrderEntity
     * @return
     */
    @RequestMapping(value = "/listUp")
    @ResponseBody
    public Map<String, Object> listUp(TransferOrderEntity transferOrderEntity) {
        Map<String, Object> paramsMap = getAllParameter();
        Map<String, Object> map = new HashMap<>(4);
        return map;
    }

    /**
     * 调拨提交按钮
     * @param
     * @return
     */
    @RequestMapping(value = "/saveTransferOrder", method = {RequestMethod.POST})
    @ResponseBody
    public  Map<String,String> saveTransferOrder(@RequestBody List<TransferOrderEntity> transferOrderEntityList) {
        //将string类型数组转换成list
//         List<Map<String, Object>> transferOrdrerList = (List<Map<String, Object>>)JSONObject.parse(arrayStr);
//        if(transferOrdrerList.size() == 0) return null;

        Map<String,String> resultMap = new HashMap<>();
//        Map tempMap = transferOrdrerList.get(0);//获取一条行信息
        Boolean isLineSaveSuccess = false;
        Boolean isCommitSuccess = false;
        Map<String,Object> headerMap = new HashMap<>();
//            Long lineId = Long.parseLong(transferOrderEntity.getLineId());
//            Map wmsHeaderInfo = transferOrderDAO.getHeaderInfoById(lineId);
        TransferOrderEntity firstData = transferOrderEntityList.get(0);
        headerMap.put("headerId",firstData.getId());
        headerMap.put("createdBy",firstData.getCreator());//工号
        headerMap.put("creationDate",firstData.getCreateTime());//创建日期
        //通过调出厂区及调出仓库获取组织Id
        String fromAreaCode = firstData.getFromAreaCode();
        String fromStoreCode = firstData.getFromStoreCode();
        String fromStoreName = firstData.getFromStore();

        String toAreaCode = firstData.getToAreaCode();
        String toStoreCode = firstData.getToStoreCode();
        String toStoreName = firstData.getToStore();
        //获取tolocatorID
        Map<String,Object> toStoreMap = new HashMap();
        toStoreMap.put("entityId",toAreaCode);
        toStoreMap.put("code",toStoreCode);
        toStoreMap.put("name",toStoreName);
        Warehouse warehouseDto = warehouseDAO.getWarehouseByCode(toStoreMap);
        if (warehouseDto == null)
        {
            resultMap.put("retCode","E");
            resultMap.put("retMess","没有配置EBS库位");
            return resultMap;
        }
        String toLocatorld = warehouseDto.getLocatorId() == null ? "" : warehouseDto.getLocatorId().toString();
        headerMap.put("toLocatorld",toLocatorld);
        //获取fromLocatorID
        Map<String,Object> fromStoreMap = new HashMap();
        fromStoreMap.put("code",fromStoreCode);
        fromStoreMap.put("name",fromStoreName);
        fromStoreMap.put("entityId",toAreaCode);
        Warehouse warehouseDto2 = warehouseDAO.getWarehouseByCode(fromStoreMap);
        String fromLocatorld = warehouseDto2.getLocatorId() == null ? "" : warehouseDto2.getLocatorId().toString();
        headerMap.put("fromLocatorld",fromLocatorld);

        Map<String, Object> fromAreaAndStroreInf = new HashMap<>(4);
        fromAreaAndStroreInf.put("entityId", fromAreaCode);
        fromAreaAndStroreInf.put("storeCode", fromStoreCode);
        Map<String, Object> toAreaAndStroreInf = new HashMap<>(4);
        toAreaAndStroreInf.put("entityId", toAreaCode);
        toAreaAndStroreInf.put("storeCode", toStoreCode);

        Map<String, Object> fromOrganizeMap = organizeService.selectOrganization(fromAreaAndStroreInf);
        Map<String, Object> toOrganizeMap = organizeService.selectOrganization(toAreaAndStroreInf);
        String toOrganizationId = new String();
        String fromOrganizationId = new String();

        if ("0".equals(fromOrganizeMap.get("code").toString())){
            fromOrganizationId = ((Map) fromOrganizeMap.get("data")).get("id").toString();
            headerMap.put("fromOrganizationId",fromOrganizationId);
        }
        if ("0".equals(toOrganizeMap.get("code").toString())){
            toOrganizationId = ((Map) toOrganizeMap.get("data")).get("id").toString();
            headerMap.put("toOrganizationId",toOrganizationId);
        }
        if(toOrganizationId.equals("") || fromOrganizationId.equals("")){
            resultMap.put("retCode","E");
            resultMap.put("retMess","未匹配到组织ID");
            return resultMap;
        }
        if(toOrganizationId.equals(fromOrganizationId)){
            resultMap.put("retCode","E");
            resultMap.put("retMess","来源组织与目标组织不能相同");
            return resultMap;
        }
        //userID
        String userId = getSessionUser().getUsername();
        headerMap.put("moUserId",userId);
        //其他数据
        headerMap.put("transactionTypeName","调拨出库");
        headerMap.put("centerName","采供中心");
        headerMap.put("deptName","");
        headerMap.put("subDeptName","");
        headerMap.put("groupName","");
        headerMap.put("comments","");
        headerMap.put("fromSubinvCode",firstData.getFromStoreCode());
        headerMap.put("toSubinvCode",firstData.getToStoreCode());
        String requestStr = JSONObject.toJSONString(headerMap);
        transferOrderService.insertHeader(headerMap);
        interfaceLogDAO.insertLog("Cux_Wms_Diaobo_Pkg.Insert_Header", "调拨头信息",
                requestStr, JSONObject.toJSONString(headerMap), "", "");
        if(headerMap.containsKey("retCode")) {
            for (TransferOrderEntity line: transferOrderEntityList){
                if(headerMap.get("retCode").toString().equals("S")) {
                    //保存行
                    try{
                        Map<String,Object> insertLineResult = transferOrderService.saveTransOrderMap(headerMap,line,"save");
                        if(insertLineResult.containsKey("retCode")) {
                            if(insertLineResult.get("retCode").toString().equals("E")) {
                                isLineSaveSuccess = false;
                                resultMap.put("retCode",insertLineResult.get("retCode").toString());
                                resultMap.put("retMess","保存行信息失败"+insertLineResult.get("retMess").toString());
                                break;
                            } else {
                                isLineSaveSuccess = true;
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    resultMap.put("retCode",headerMap.get("retCode").toString());
                    resultMap.put("retMess","保存头信息失败"+headerMap.get("retMess").toString());
                }
            }
        }

        //所有行insert后
        if(isLineSaveSuccess == true) {
            //执行commit
            for (TransferOrderEntity line: transferOrderEntityList){
                try{
                    Map<String,Object> commitLineResult = transferOrderService.saveTransOrderMap(headerMap,line,"commit");
                    if(commitLineResult.containsKey("retCode")) {
                        if(commitLineResult.get("retCode").toString().equals("E")) {
                            isCommitSuccess = false;
                            resultMap.put("retCode",commitLineResult.get("retCode").toString());
                            resultMap.put("retMess","出库失败"+commitLineResult.get("retMess").toString());
                            break;
                        } else {
                            isCommitSuccess = true;
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        if(isCommitSuccess == true){
            resultMap.put("retCode","S");
            resultMap.put("retMess","保存成功");
        }

        return resultMap;
    }

    /**
     * 批量保存 并更新送退货行表
     *
     * @param
     * @return Map<String, Object>
     */
    @PostMapping(value = "/saveBatch/{type}")
    @ResponseBody
    public Map<String, Object> saveBatch(@RequestBody List<YclInOutFlowEntity> yclInOutFlowEntities,@PathVariable("type")String type) {
        Map<String, Object> map = new HashMap<>(2);
        try {
            if (yclInOutFlowEntities.size() > 0) {
                List<Map<String, Object>> line = new ArrayList<>();
                Map<String, Object> paramsMap = new HashMap<>(2);
                paramsMap.put("tranCode", yclInOutFlowEntities.get(0).getBusinessCode());
                List<TransferOrderEntity> ts = transferOrderDAO.getPageList(paramsMap);
                List<YclInOutFlowEntity> inEn = new ArrayList<>();
                List<Map<String, Object>> processList = new ArrayList<>();


                for (int i = 0; i < ts.size(); i++) {
//                Map<String, Object> l = new HashMap<>();
//                l.put("LAY_TABLE_INDEX",i+1);
//                l.put("tempId",ts.get(i).getLineId());
//                l.put("lineId",ts.get(i).getLineId());
//                l.put("businessCode",ts.get(i).getTranCode());
//                l.put("areaCode",ts.get(i).getToAreaCode());
//                l.put("storeCode",ts.get(i).getToStoreCode());
//                l.put("fromLocator",ts.get(i).getFromLocator());
//                l.put("quantity",ts.get(i).getOutQuantity());
//                l.put("materialCode",ts.get(i).getMaterialCode());
//                l.put("materialName","");
//                l.put("lotsNum",ts.get(i).getLotsNum());
//                l.put("state","1");
//                l.put("inoutType","1");
//                l.put("locatorCode",ts.get(i).getToLocator());
//                l.put("updownQuantity",ts.get(i).getOutQuantity());
//                line.add(l);

                    YclInOutFlowEntity en = new YclInOutFlowEntity();
                    en.setAreaCode(ts.get(i).getToAreaCode());
                    en.setStoreCode(ts.get(i).getToStoreCode());
                    en.setLocatorCode(ts.get(i).getToLocator());
                    en.setMaterialCode(ts.get(i).getMaterialCode());
                    en.setMaterialName(ts.get(i).getMaterialName());
                    en.setLotsNum(ts.get(i).getLotsNum());
                    en.setUpdownQuantity(new BigDecimal(ts.get(i).getOutQuantity()));
                    en.setInoutType("0");
                    en.setCreateTime(DateUtil.date());
                    en.setCreateUser(getSessionUser().getUsername());
                    inEn.add(en);
                }
                Map<String, String> ret = new HashMap<>();
                if ("3".equals(type)) {
                    //回传EBS
                    ret = saveTransferOrder(ts);
                    if ("E".equals(ret.get("retCode"))) {
                        map.put("result", false);
                        map.put("msg", ret.get("retMess"));
                        return map;
                    }
                } else if ("2".equals(type)) {
                    //子库存转移
                    ret = subTransfer(ts);
                    if ("1".equals(ret.get("retCode"))) {
                        map.put("result", false);
                        map.put("msg", ret.get("retMess"));
                        return map;
                    }
                }

                yclInOutFlowService.saveBatch(inEn);
                for (int i = 0; i < ts.size(); i++) {
                    updateLineState(ts.get(i).getLineId(), "1");
                }
                updateHeadState(ts.get(0).getId(), "1");
            }

            for (int i = 0; i < yclInOutFlowEntities.size(); i++) {
                yclInOutFlowEntities.get(i).setCreateTime(DateUtil.date());
                yclInOutFlowEntities.get(i).setCreateUser(getSessionUser().getUsername());
            }

            boolean result = yclInOutFlowService.saveBatch(yclInOutFlowEntities);
            map.put("result", result);
            map.put("msg", result ? "操作成功！" : "操作失败！");
        }catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    @PostMapping(value = "/subTransfer")
    @ResponseBody
    @Transactional
    public Map<String, String> subTransfer(@RequestBody List<TransferOrderEntity> transferOrderEntityList) {
        OperationOtherHeadDTO headDTO = new OperationOtherHeadDTO();
        Map resultMap  = new HashMap();
        try {
            TransferOrderEntity firstData = transferOrderEntityList.get(0);
            String fromAreaCode = firstData.getFromAreaCode();
            String fromStoreCode = firstData.getFromStoreCode();
            Map<String, Object> fromAreaAndStroreInf = new HashMap<>(4);
            fromAreaAndStroreInf.put("entityId", fromAreaCode);
            fromAreaAndStroreInf.put("storeCode", fromStoreCode);
            Map<String, Object> fromOrganizeMap = organizeService.selectOrganization(fromAreaAndStroreInf);
            if ("0".equals(fromOrganizeMap.get("code").toString())) {
                Long fromOrganizationId = Long.parseLong(((Map) fromOrganizeMap.get("data")).get("id").toString());
                headDTO.setOrganizationId(fromOrganizationId);
            }
            headDTO.setBusinessType("OUTBOND");//单据类型
//        headDTO.setTransactionDate(new Date());//事务处理日期
            headDTO.setBusinessPurpose("13-子库存转移");//事务处理类型
            headDTO.setDepartCode(firstData.getDept());//部门号
//        headDTO.setOperationSeqNum("");//工序
//        headDTO.setOperationMachine("");//机台
            headDTO.setPreparer(getSessionUser().getUsername());//申请人工号
//        headDTO.setRemark(firstData.getRemark() == null ? "" : firstData.getRemark().toString());
            headDTO.setUser(getSessionUser().getUsername());//当前操作人员工号
//        headDTO.setLyytCode("");//领用用途
//        headDTO.setLoad("");//装车通知单
//        headDTO.setVendorName("");//供应商
            String request = JSONObject.toJSONString(headDTO);
            otherService.createHead(headDTO);
            interfaceLogDAO.insertLog("cux_wms_inv_misctx_pkg.create_head", "创建或更新其他出入库头信息",
                    request, JSONObject.toJSONString(headDTO), "", "");
            if (headDTO.getRetCode().equals(Constant.ERROR)) {
                resultMap.put("retCode", "1");
                resultMap.put("retMess", headDTO.getRetMess());
                return resultMap;
            }

            Warehouse warehouse = warehouseDAO.findByCodeAndEntityId(firstData.getFromStoreCode(), firstData.getFromAreaCode());
            if (ObjectUtil.isNull(warehouse) || ObjectUtil.isNull(warehouse.getLocatorId())) {
                resultMap.put("code", 1);
                resultMap.put("msg", "EBS来源虚拟库位不存在，请检查！");
                return resultMap;
            }

            Warehouse warehouseTo = warehouseDAO.findByCodeAndEntityId(firstData.getToStoreCode(), firstData.getToAreaCode());
            if (ObjectUtil.isNull(warehouseTo) || ObjectUtil.isNull(warehouseTo.getLocatorId())) {
                resultMap.put("code", 1);
                resultMap.put("msg", "EBS目标虚拟库位不存在，请检查！");
                return resultMap;
            }

            for (TransferOrderEntity line : transferOrderEntityList) {
                OperationOtherLineDTO lineDTO = new OperationOtherLineDTO();
                lineDTO.setHeadId(headDTO.getHeadId());
                lineDTO.setOrganizationId(headDTO.getOrganizationId());
//            lineDTO.setLineNum(Long.valueOf(line.getLineNum()));
                lineDTO.setLineNum(Long.valueOf(line.getLineId()));

                lineDTO.setMaterialCode(line.getMaterialCode());
                lineDTO.setPrimaryUnit(line.getPrimaryUnit());//物料单位
                lineDTO.setTransactionQuantity(new BigDecimal(line.getOutQuantity()));
                lineDTO.setSubCode(line.getFromStoreCode());//子库
                lineDTO.setLocator(warehouse.getLocatorId());
                lineDTO.setRemark(line.getRemark());
                lineDTO.setTransferSubCode(line.getToStoreCode());
                lineDTO.setTransferLocator(warehouseTo.getLocatorId());
                lineDTO.setUser(headDTO.getUser());
                otherService.createLine(lineDTO);
                if (lineDTO.getRetCode().equals(Constant.ERROR)) {
                    resultMap.put("code", "1");
                    resultMap.put("msg", lineDTO.getRetMess());
                    return resultMap;
                }
                OperationOtherValidDTO validDTO = new OperationOtherValidDTO();
                validDTO.setHeadId(lineDTO.getHeadId());
                otherService.validateData(validDTO);
                if (validDTO.getRetCode().equals(Constant.ERROR)) {
                    resultMap.put("retCode", "1");
                    resultMap.put("retMess", validDTO.getRetMess());
                    return resultMap;
                }
                OperationOtherProcessDTO processDTO = new OperationOtherProcessDTO();
                processDTO.setHeadId(lineDTO.getHeadId());
                processDTO.setLineId(lineDTO.getLineId());
                otherService.process(processDTO);
                if (processDTO.getRetCode().equals(Constant.ERROR)) {
                    resultMap.put("retCode", "1");
                    resultMap.put("retMess", processDTO.getRetMess());
                    return resultMap;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        resultMap.put("retCode", "0");
        resultMap.put("retMess", "提交成功");
        return resultMap;
    }


    /**
     * 根据移位调拨表主键ID查询主表和行表信息
     * @param id
     * @return
     */
    @PostMapping(value = "/selectTransferOrderEntity")
    @ResponseBody
    public TransferOrderEntity selectTransferOrderEntity(@RequestParam String id){
        TransferOrderEntity transferOrderEntity = transferOrderService.findById(id);
        Map<String,Object> map = new HashMap<>();
        map.put("tran_id",transferOrderEntity.getId());
        List<TransferOrderLineEntity> list = transferOrderLineService.getTransferOrderLines(map);
        if(list.size()>0){
            transferOrderEntity.setLine(list);
        }
        return transferOrderEntity;
    }

}
